<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="电话号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入电话号码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="报名时间" prop="regisTime">
        <el-date-picker clearable v-model="queryParams.regisTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择报名时间">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="待缴纳费用" prop="payFees">
        <el-input v-model="queryParams.payFees" placeholder="请输入待缴纳费用" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="报名的课程" prop="courseId">
        <el-input v-model="queryParams.courseId" placeholder="请输入报名的课程" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="学历信息" prop="education">
        <el-select v-model="queryParams.education" placeholder="请输入学历信息" clearable @keyup.enter="handleQuery"
          style="width: 150px;">
          <el-option label="本科" value="本科" />
          <el-option label="大专" value="大专" />
          <el-option label="高中" value="高中" />
          <el-option label="初中" value="初中" />
          <el-option label="小学" value="小学" />
        </el-select>
      </el-form-item>
      <el-form-item label="监护人联系电话" prop="emergency" class="inline-form-item">
        <el-input v-model="queryParams.emergency" placeholder="请输入监护人联系电话" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请输入性别" clearable @keyup.enter="handleQuery"
          style="width: 150px;">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item label="学生来源" prop="studentSource" style="width:200px;">
        <el-select v-model="queryParams.studentSource" placeholder="请选择学生来源" clearable @change="handleQuery">
          <el-option label="自主报名" value="自主报名" />
          <el-option label="跟进报名" value="跟进报名" />

        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['registration:registration:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['registration:registration:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['registration:registration:export']">导出</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="registrationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="regisId" />
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="电话号码" align="center" prop="phone" />
      <el-table-column label="地址" align="center" prop="stuaddr" />
      <el-table-column label="学生身份证" align="center" prop="stucardnumber" />
      <el-table-column label="学生家长名字" align="center" prop="stufamilyname" />
      <el-table-column label="报名时间" align="center" prop="regisTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.regisTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="待缴纳费用" align="center" prop="payFees" />
      <el-table-column label="报名的课程" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click=" getCourseList(scope.row.courseId)">
            查看课程
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="缴费情况" align="center" prop="status"
        :formatter="(row) => row.status === 0 ? '未缴费' : row.status === 1 ? '已缴费' : '已退费'" />
      <el-table-column label="学历信息" align="center" prop="education" />
      <el-table-column label="监护人联系电话" align="center" prop="emergency" />
      <el-table-column label="性别" align="center" prop="gender" :formatter="(row) => row.gender === 0 ? '男' : '女'" />
      <el-table-column label="用户账号" align="center" prop="uid" />
      <el-table-column label="学生来源" align="center" prop="studentSource" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['registration:registration:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['registration:registration:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 课程预览框 -->
    <el-dialog v-model="courseDetailVisible" :title="`课程详情 (共 ${tbcourseList.length} 门课程)`" width="600px"
      class="course-detail-dialog">
      <!-- 加载状态 -->
      <div v-if="courseLoading" class="loading-state">
        <el-icon class="is-loading">
          <Loading />
        </el-icon>
        <span>课程信息加载中...</span>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="courseError" class="error-state">
        <el-icon>
          <CircleCloseFilled />
        </el-icon>
        <span>{{ courseError }}</span>
      </div>

      <!-- 课程列表 -->
      <div v-else-if="tbcourseList.length > 0" class="course-content">
        <div v-for="(course, index) in tbcourseList" :key="course.courseId" class="course-item">
          <el-descriptions :column="1" border size="large" direction="vertical">
            <el-descriptions-item label="课程名称" label-class-name="desc-label">
              <span class="course-name">{{ course.courseName }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="上课次数" label-class-name="desc-label">
              <el-icon>
                <Clock />
              </el-icon>
              <span>{{ course.time }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="课程费用" label-class-name="desc-label">
              <span class="course-fee">¥{{ course.price }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="课程描述" label-class-name="desc-label">
              <div class="course-description">
                {{ course.information }}
              </div>
            </el-descriptions-item>
          </el-descriptions>

          <!-- 添加分隔线（最后一个课程不显示） -->
          <el-divider v-if="index < tbcourseList.length - 1" />
        </div>
      </div>

      <!-- 无数据提示 -->
      <div v-else class="empty-state">
        <el-icon>
          <Warning />
        </el-icon>
        <span>暂无课程数据</span>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="courseDetailVisible = false" class="close-btn">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>


    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改报名信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="registrationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item label="地址" prop="stuaddr">
          <el-input v-model="form.stuaddr" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="学生身份证" prop="stucardnumber">
          <el-input v-model="form.stucardnumber" placeholder="请输入学生身份证" />
        </el-form-item>
        <el-form-item label="学生家长名字" prop="stufamilyname">
          <el-input v-model="form.stufamilyname" placeholder="请输入学生家长名字" />
        </el-form-item>

        <!-- <el-form-item label="待缴纳费用" prop="payFees">
          <el-input v-model="form.payFees" placeholder="请输入待缴纳费用" />
        </el-form-item> -->

        <el-form-item label="报名的课程" prop="courseId">
          <el-select v-model="form.courseId" multiple :placeholder="courseName" style="width: 100%">
            <el-option v-for="item in couresList" :key="item.value" :label="item.courseName" :value="item.courseId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学历信息" prop="education">
          <el-select v-model="form.education" placeholder="请输入学历信息">
            <el-option label="本科" value="本科" />
            <el-option label="专科" value="专科" />
            <el-option label="高中" value="高中" />
            <el-option label="初中" value="初中" />
            <el-option label="小学" value="小学" />
          </el-select>
        </el-form-item>
        <el-form-item label="监护人联系电话" prop="emergency">
          <el-input v-model="form.emergency" placeholder="请输入监护人联系电话" />
        </el-form-item>
        <el-form-item label="缴费情况" prop="status">
          <el-select v-model="form.status" placeholder="请选择缴费情况">
            <el-option label="未缴费" :value="0" />
            <el-option label="已缴费" :value="1" />
            <el-option label="已退费" :value="2" />
          </el-select>
        </el-form-item>
        <!-- 带样式的单选框 -->
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio-button :label="0" :class="{ 'active-radio': form.gender === 0 }">
              男
            </el-radio-button>
            <el-radio-button :label="1" :class="{ 'active-radio': form.gender === 1 }">
              女
            </el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="学生来源" prop="studentSource">
          <el-select v-model="form.studentSource" placeholder="请输入生源信息">
            <el-option label="自主报名" value="自主报名" />
            <el-option label="跟进报名" value="跟进报名" />
            <el-option label="线索池报名" value="线索池报名" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Registration">
import { listRegistration, getRegistration, delRegistration, addRegistration, updateRegistration, } from "@/api/registration/registration"
import { getTbcourse, listTbcourse } from "@/api/tbcourse/tbcourse"
import { reactive, } from "vue"
import { ref } from "vue"


const { proxy } = getCurrentInstance()

const registrationList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")



// 获取报名人员的课程表信息
const tbcourseList = ref([])
const courseDetailVisible = ref(false)
const courseLoading = ref(false)
const courseError = ref(null)
async function getCourseList(courseIds) {
  courseDetailVisible.value = true;
  courseLoading.value = true;
  courseError.value = null;

  try {
    // 如果传入的是字符串，先分割
    const ids = typeof courseIds === 'string'
      ? courseIds.split(',').map(id => id.trim())
      : courseIds;

    // 并行请求所有课程详情
    const requests = ids.map(id => getTbcourse(id));
    const results = await Promise.all(requests);

    // 提取有效数据
    tbcourseList.value = results
      .filter(res => res && res.data)
      .map(res => res.data);

  } catch (err) {
    courseError.value = '获取课程信息失败: ' + (err.message || '未知错误');
    console.error('获取课程信息失败:', err);
  } finally {
    courseLoading.value = false;
  }
}
// 获取课程信息
const couresList = ref([]);
const courseParam = reactive({
  pageNum: 1,
  pageSize: 100
});
function getallcouresList() {
  listTbcourse(courseParam).then(response => {
    couresList.value = response.rows
  })
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    phone: null,
    regisTime: null,
    payFees: null,
    courseId: null,
    status: null,
    education: null,
    emergency: null,
    gender: null,
    uid: null,
    studentSource: null,
    stuaddr: null,
    stufamilyname: null,
    stucardnumber: null
  },
  rules: {
    userName: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],


  }
})

const { queryParams, form, rules } = toRefs(data)

const courseName = ref("")

const promise = reactive(null)
/** 查询报名信息列表 */
function getList() {
  loading.value = true
  listRegistration(queryParams.value).then(response => {
    registrationList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    regisId: null,
    userName: null,
    phone: null,
    regisTime: null,
    payFees: null,
    courseId: null,
    status: null,
    education: null,
    emergency: null,
    gender: null,
    uid: null,
    studentSource: null,
    stuaddr: null,
    stufamilyname: null,
    stucardnumber: null,
    stuId: null
  }
  proxy.resetForm("registrationRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.regisId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加报名信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _regisId = row.regisId || ids.value;
  getRegistration(_regisId).then(response => {
    form.value = response.data;
    const ids = typeof form.value.courseId === 'string'
      ? form.value.courseId.split(',').map(id => id.trim())
      : form.value.courseId;
    const requests = ids.map(id => getTbcourse(id));
    const results = Promise.all(requests);

    results.then(data => {
      courseName.value = data.map(item => item.data.courseName).join(',');
      open.value = true;
      title.value = "修改报名信息";
    }).catch(error => {
      console.error('Error fetching courses:', error);
    });
  }).catch(error => {
    console.error('getRegistration 函数错误:', error);
  });
}



/** 提交按钮 */
async function submitForm() {
  const ids = typeof form.value.courseId === 'string'
    ? form.value.courseId.split(',').map(id => id.trim())
    : form.value.courseId;
  const requests = ids.map(id => getTbcourse(id));
  const results = await Promise.all(requests);
  const prices = results.map(item => Number(item.data.price)) || 0;
  form.value.payFees = prices.reduce((sum, price) => sum + price, 0);
  console.log(form.value.payFees);
  proxy.$refs["registrationRef"].validate(valid => {
    if (valid) {
      form.value = {
        ...form.value,
        courseId: Array.isArray(form.value.courseId)
          ? form.value.courseId.join(',')
          : form.value.courseId || ''
      };
      if (form.value.regisId != null) {
        console.log(form.value)
        updateRegistration(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        console.log(form.value)
        addRegistration(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _regisIds = row.regisId || ids.value
  proxy.$modal.confirm('是否确认删除报名信息编号为"' + _regisIds + '"的数据项？').then(function () {
    return delRegistration(_regisIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('registration/registration/export', {
    ...queryParams.value
  }, `registration_${new Date().getTime()}.xlsx`)
}
getList()
getallcouresList()
</script>
 